<?php
namespace SysAdmin\Controller;
ob_end_clean();
header("content-type:text/html;charset=utf-8");

class UserController extends LoginTrueController
{
    public function Add()
    {
        $this->LoginTrue();

        $this->display("add");
    }

	public function AddAction(){
		
		
        $txt_loginname = $_POST["txt_tel"];
        if (!$txt_loginname) {
            $this->error("手机号不能为空");
            exit();
        }
        if ($this->check_loginname($txt_loginname)) {
            $this->error("手机号重复，请重新获取!");
            exit();
        }
		
		
        //验证身份证是不是重复
		
		$rid = $_POST['txt_rid'];
        if (!$rid) {
            $this->error("推荐码不能为空");
            exit();
        }
		
		
        if (!$_POST["txt_bankname"]) {
            $this->error("商家姓名不能为空");
            exit();
        }
        if (!$_POST["txt_pwd1"]) {
            $this->error("请填写密码");
            exit();
        }
		

		$upload = new \Think\Upload();// 实例化上传类
		$upload->rootPath = './uploads/';
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->saveName = array('uniqid','');
		$upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
		$upload->autoSub  = true;
		$upload->subName  = array('date','Ymd');
		$info   =   $upload->upload();
		if(!$info) {// 上传错误提示错误信息
			$this->error($upload->getError());
		}else{// 上传成功 获取上传文件信息
			foreach($info as $file){
				$file_path =  $file['savepath'].$file['savename'];
			}
		}
        if (!$file_path) {
            $this->error("请选择微信二维码上传");
            exit();
        }
		
		
        $r_user = M("users")->where("tuijianma='{$rid}'")->find();//rpath根据推荐人来计算
		if(!$r_user){
            $this->error("推荐人信息错误");
            exit();
		}
        if ($r_user['rpath']) {
            $data['rpath'] = $r_user['rpath'] . "," . $r_user['id'];//推荐rpath
        } else {
            $data['rpath'] = $r_user['id'];//推荐rpath
        }
       
	   
        $data['wximg'] = $file_path;//微信二维码
        $data['ceng'] = $r_user_p['ceng'] + 1;//层
        $data['dai'] = $r_user['dai'] + 1;
        $data['standardlevel'] = '0';//刚开始就是临时会员
        $data["loginname"] = $txt_loginname;
        $data["tuijianma"] = $this->SysSet['inviteStart'].$this->get_random(3);;
        $data["truename"] = $_POST['txt_bankname'];
        $data["tel"] = $txt_loginname;
        $data["rid"] = $r_user['id'];
        $data["pwd1"] = md5(trim($_POST["txt_pwd1"]));
        $data["pwd2"] = md5(trim($_POST["txt_pwd1"]));
        $data["states"] = 0;
        $data["addtime"] = time();
		
		
       
        $result = M('users')->add($data);
        if ($result) {
            $this->success("添加成功",U("lists"));
			exit;
        } else {
            $this->error("注册失败,请重新注册");
            exit();
        }

	}
	
    function get_random($len = 3)
    {
        //range 是将10到99列成一个数组
        $numbers = range(10, 99);
        //shuffle 将数组顺序随即打乱
        shuffle($numbers);
        //取值起始位置随机
        $start = mt_rand(1, 10);
        //取从指定定位置开始的若干数
        $result = array_slice($numbers, $start, $len);
        $random = "";
        for ($i = 0; $i < $len; $i++) {
            $random = $random . $result[$i];
        }
        //		return 'h'.$random;  //提示总共八位字符 我删除一个吧
        return 'h'.substr($random, 0, -1);
    }


    function check_loginname($biaohao)
    {

        $users = M("users")->field("loginname")->where("loginname='" . $biaohao . "'")->find();
        if (empty($users))
            return false;
        return true;
    }

    public function CheckMobile()
    {
        $getusername = str_replace('\'', '', stripslashes($_GET["username"]));
        $id = str_replace('\'', '', stripslashes($_GET["id"]));

        if ($id) {
            //修改查询
            $users = M("users")->field("loginname")->where("tel='" . $getusername . "' and id<>{$id}")->find();
        } else {
            $users = M("users")->field("loginname")->where("tel='" . $getusername . "'")->find();
        }
        if (empty($users)) {
            echo "0";
            exit();
        }
        echo "1";
        exit();
    }

    public function CheckTuijian()
    {
        $getusername = str_replace('\'', '', stripslashes($_GET["username"]));

        $users = M("users")->field("loginname")->where("tuijianma='" . $getusername . "'")->find();

        if (empty($users)) {
            echo "0";
            exit();
        }
        echo "1";
        exit();
    }

	

    public function Lists()
    {
        $this->LoginTrue();
        $userLists = M("users");

        $rs_suserLists = $userLists->where()->order("addtime desc")->select();
		foreach($rs_suserLists as $key=>$val){
			
			$rs_suserLists[$key]["rname"] = $userLists->where("id=".$val['rid'])->getField("loginname");
			
			$rs_suserLists[$key]["invite_count"] = $userLists->where("rid=".$val['id'])->count();
			$rs_suserLists[$key]["team_count"] = $userLists->where("FIND_IN_SET($val[id],rpath)")->count();
			
		}
        $this->assign("rs_staffLists", $rs_suserLists);
        $year = date("Y");
        $this->assign("year", $year);

        $this->display();
    }

    /**
     * 临时会员列表 ------ add by pp
     */
    public function Ls_lists()
    {
        $this->LoginTrue();
        $userLists = M("users");

        $rs_suserLists = $userLists->where('states=0')->order("addtime desc")->select();

        $this->assign("rs_staffLists", $rs_suserLists);
        $year = date("Y");
        $this->assign("year", $year);

        $this->display();
    }

	

    public function dongjie()
    {
        $this->LoginTrue();
        $staffShow = M("users");
        //删除临时会员  --- add  by  pp
       
	   
        $stId = $_GET["id"];
        $status = $_GET["status"];
		
		if($status==2)
			$status = 0;
		
        $loginname = $staffShow->field('loginname,lockuser')->where("id={$stId}")->find();
        if (!$loginname) {
            $this->error("不存在此用户");
            return;
        }
		if($loginname['lockuser'] == $status){
			$this->error("不需要更改状态");
		}
		($staffShow->where("id={$stId}")->setField("lockuser",$status));
		
		$this->success("操作成功",U("lists"));
		exit;
	
	}
    public function Del()
    {

        $this->LoginTrue();
        $staffShow = M("users");
        //删除临时会员  --- add  by  pp
       
	   
        $stId = $_GET["stId"];
		if($stId==1){
            $this->error("不存在此用户");
            return;
		}
        $loginname = $staffShow->field('loginname')->where("id={$stId}")->find();
        if (!$loginname) {
            $this->error("不存在此用户");
            return;
        }
        $loginname = $loginname['loginname'];

        //判断下面有无推荐人
        $tarray = $staffShow->field('loginname')->where("rid={$stId}")->find();
        if ($tarray) {
            $this->error("此用户下有推荐人 不能删除");
            return;
        }

        $rs_staffShow = $staffShow->where("id={$stId}")->delete();
		$this->success("删除成功",U("lists"));
		exit;
        $this->assign("rs_staffShow", $rs_staffShow);
        $this->display();
    }

    /**
     * 管理登录日志
     */
    public  function admin_login_log(){
        $log_info=M('admin_login')->order(' id desc')->select();
        $this->assign('log_info',$log_info);
        $this->display();

    }
    /**
     * 会员登录日志
     */
    public  function users_login_log(){
        $log_info=M('users_login')->order(' id desc')->select();
//        print_r($log_info);die;
        $this->assign('log_info',$log_info);
        $this->display();

    }

    public function DelAction()
    {
        $this->LoginTrue();
        $stId = $_GET["stId"];
        $usersShow = M("users");

        $loginname = $usersShow->field('loginname')->where("id={$stId}")->find();
        if (!$loginname) {
            $this->error("不存在此用户");
            return;
        }
        $loginname = $loginname['loginname'];

        //判断下面有无推荐人
        $tarray = $usersShow->field('loginname')->where("rid={$loginname}")->find();
        if ($tarray) {
            $this->error("此用户下有推荐人 不能删除");
            return;
        }


        $result = $usersShow->where("id={$stId}")->delete();
        if ($result) {
            $this->success("删除成功", U("lists"));
        } else {
            $this->error("删除失败");
        }
    }

	

	
	
    public function Update()
    {
        $this->LoginTrue();
        $stId = $_GET["stId"];

        $staffShow = M("users");
        $rs_staffInfo = $staffShow->where("id={$stId}")->find();


        $this->assign("rs_staffInfo", $rs_staffInfo);


        $this->display();
    }

	public function GoIndex(){
		
        $staffAdd = M("users");
        $this->LoginTrue();
        $stId = $_GET["stId"];
        $rs=$staffAdd->where("id={$stId}")->find();
		if(!$rs){
			$this->error("数据异常");
		}
		
            $system=M("system");
            $rs_system=$system->field("sCheckCodeSwitch,sErrorPwdLockNum,sLoginTimeout")->where("sId=1")->find();
			
		 session("nvip_member_id",$rs["id"]);
		session("nvip_member_tuijianma",$rs["tuijianma"]);
		session("nvip_nvip_member_User",$rs["loginname"]);
		session("nvip_member_time",time());
		session("nvip_member_level",$rs['standardlevel']);
		$_SESSION['nvip_user_expiretime'] = time() + (($rs_system["sLoginTimeout"])*60);
		$loginTime=date("Y-m-d H:i:s");
		session("nvip_member_loginTime",$loginTime);

	 session("nvip_member_states",$rs["states"]);

		$this->success("登录成功正在跳转",U('Home/Index/index/'));
		
	}
    public function UpdateAction()
    {
        $this->LoginTrue();
        $stId = $_GET["stId"];
        $staffAdd = M("users");
        $data = $_POST;
        $uinfo=$staffAdd->where("id={$stId}")->find();
      
	  
        if ($_POST["txt_pwd1"]) {
            $data["pwd1"] = md5($_POST["txt_pwd1"]);
            $data["pwd2"] = md5($_POST["pwd1"]);
        }
		
		$mobile = $_POST["mobile"];
		
		$users=M("users")->field("loginname")->where("loginname='".$mobile."' and id<>$stId")->find();
		if(!empty($users)){
			$this->error("手机号码重复");
		}
		$data["loginname"] = $mobile;
		$data["tel"] = $mobile;
		
		$upload = new \Think\Upload();// 实例化上传类
		$upload->rootPath = './uploads/';
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->saveName = array('uniqid','');
		$upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
		$upload->autoSub  = true;
		$upload->subName  = array('date','Ymd');
		$info   =   $upload->upload();
		
		if(!$info) {// 上传错误提示错误信息
			//$this->error($upload->getError());
		}else{// 上传成功 获取上传文件信息
		
			foreach($info as $file){
				$file_path =  $file['savepath'].$file['savename'];
			}
		}
        if ($file_path) {
            
			$data['wximg'] = $file_path;//微信二维码
        }
		
        $result = $staffAdd->where("id={$stId}")->save($data);
        if ($result) {
            $this->success("修改会员信息成功", U("lists"));
        } else {
            $this->error("修改会员信息失败；没做改动");
        }
    }


    /**
     * 推荐关系
     **/
    public function Affectlists()
    {
        $this->LoginTrue();
        $users = M("users");

        $loginname = isset($_POST['search_loginname']) ? $_POST['search_loginname'] : "";
        if ($loginname) {
            $top_info = $users->field("id,pid,rid,loginname,standardlevel")->where("loginname='{$loginname}'")->order("id asc")->find();
        } else {
            $top_info = $users->field("id,pid,rid,loginname,standardlevel")->order("id asc")->find();
            $loginname = $top_info['loginname'];
        }
        $a_lists = $this->getZhituiTree($top_info, $users);
        $top_info['childrencount'] = count($a_lists);
        $top_info['level'] = GetLevel($top_info["standardlevel"]);
        //$a_lists[$top_info['loginname']]['childrencount'] = count($str);
        //$a_lists[$top_info['loginname']]['children'] = $str;

        // print_r($a_lists);

        $this->assign("a_lists", $a_lists);
        $this->assign("top_info", $top_info);

        $this->display();
    }

	
	
	
    public function add_admin_user(){
        if (IS_POST){
            if(!$_POST['aUser']){
                $this->error('请填写管理账号');die;
            }
            if(!($_POST['aPwd']==$_POST['aPwd_2'])  ||  (!$_POST['aPwd'])){
                $this->error('两次密码不一致');die;
            }
            if(M('admin')->where("aUser='{$_POST['aUser']}'")->find()){
                $this->error('此账号已经存在');die;
            }
            M('admin')->add(array('aUser'=>$_POST['aUser'],'aPwd'=>md5($_POST['aPwd'])));
            $this->error('管理账号添加成功');
        }
        $this->display();
    }

    public function update_admin_user(){
        $info=M('admin')->where("aUser='{$_SESSION['aUser']}'")->find();
        $this->assign('aUser',$info['aUser']);
        if (IS_POST){
            if(!(md5($_POST['aPwd_y'])==$info['aPwd'])){
                $this->error('原始密码不正确');die;
            }
            if(!($_POST['aPwd']==$_POST['aPwd_2'])  ||  (!$_POST['aPwd'])){
                $this->error('两次密码不一致');die;
            }
            M('admin')->where("aUser='{$_SESSION['aUser']}'")->save(array('aPwd'=>md5($_POST['aPwd'])));
            $this->error('管理密码修改成功');
        }
        $this->display();
    }
	


    /*
    * 订单列表
    */
    public function orderlist()
    {
        $userid = I("search_loginname") ? I("search_loginname") : "";
        $from = I("from") ? strtotime(I("from")) : "";
        $until = I("until") ? strtotime(I("until")) : "";

        $where = " 1=1 ";

        $where .= $userid ? " AND loginname like '%$userid%'" : "";
        $where .= $from ? " AND adddate >= $from " : "";
        $where .= $until ? " AND adddate <= $from " : "";

		 $count = M("usersjinfo")->where($where)->count();
		 
		 $Page = Page($count, $this->pagesize);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();
		
		$shList = M("usersjinfo")->where($where)->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
		foreach($shList as $key=>$val){
			
			$shList[$key]['user'] = M("users")->where("id=".$val['user_id'])->field("truename")->find();
			$shList[$key]['levelname'] = GetLevel($val['curlevel']);
			$shList[$key]['targetlevelname'] = GetLevel($val['targetlevel']);
			if($shList[$key]['shuser1']){
				$shList[$key]['sh1ts'] = M("tousuinfo")->where("tsorderid=$val[id] and tsuserobj=$val[shuser1] and tstype=1")->find();
			//	$shList[$key]['sh1ts'] = $shList[$key]['sh1ts'] ? "是" : "否";

				
				$shList[$key]['sh1tsdz'] = M("tousuinfo")->where("tsorderid=$val[id] and tsuserobj=$val[shuser1] and tstype=2")->find();
				//$shList[$key]['sh1tsdz'] = $shList[$key]['sh1tsdz'] ? "是" : "否";
				$shList[$key]['sh1dianzanname'] = $shList[$key]['sh1dianzan']==1 ? "是" : "否";
			}
			if($shList[$key]['shuser2']){
				$shList[$key]['sh2ts'] = M("tousuinfo")->where("tsorderid=$val[id] and tsuserobj=$val[shuser2] and tstype=1")->find();
				//$shList[$key]['sh2ts'] = $shList[$key]['sh2ts'] ? "是" : "否";
				$shList[$key]['sh2tsdz'] = M("tousuinfo")->where("tsorderid=$val[id] and tsuserobj=$val[shuser2] and tstype=2")->find();
			//	$shList[$key]['sh2tsdz'] = $shList[$key]['sh2tsdz'] ? "是" : "否";
				$shList[$key]['sh2dianzanname'] = $shList[$key]['sh2dianzan']==1 ? "是" : "否";
			}
			
			
			$shList[$key]['shuser1'] =$val['shuser1'] ?: '-';
			$shList[$key]['shuser2'] =$val['shuser2'] ?: '-';
			$shList[$key]['status1name'] = $val['shuser1'] ? $this->GetStatus($val['status1']) : '-';
			$shList[$key]['status2name'] =  $val['shuser2'] ? $this->GetStatus($val['status2']) : '-';
			$shList[$key]['shtime1date'] = ($val['status1']!=0 && $val['shuser1']) ?  date('Y-m-d H:i:s',$val['shtime1']) :"-";
			$shList[$key]['shtime2date'] = ($val['status2']!=0 && $val['shuser2']) ?   date('Y-m-d H:i:s',$val['shtime2']) : "-";
			
			
		}
		$this->assign("shList",$shList);

     
        $this->assign("page", $show);

        $this->display();

    }
	
	public function tslists(){
		
        $userid = I("search_loginname") ? I("search_loginname") : "";
        $userid1 = I("search_loginname1") ? I("search_loginname1") : "";
        $orderid = I("orderid") ? I("orderid") : "";
		

        $where = " 1=1 ";

        $where .= $userid ? " AND tsuser like '%$userid%'" : "";
        $where .= $userid1 ? " AND tsuserobj like '%$userid1%'" : "";
        $where .= $orderid ? " AND tsorderid = $orderid" : "";
      
	  

		 $count = M("tousuinfo")->where($where)->count();
		 
		 $Page = Page($count, $this->pagesize);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();
		
		$shList = M("tousuinfo t")->field("*,(select truename from nv_users where loginname=t.tsuser) as tsusername,(select truename from nv_users where loginname=t.tsuserobj) as tsuserobjname")->where($where)->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
		foreach($shList as $key=>$val){
			
			$shList[$key]['tstypename'] =  $val['tstype'] == 2 ? "点赞" : "订单";
			$shList[$key]['addtime'] = date("Y-m-d H:i:s",$val['addtime']);
		}
		
		$this->assign("shList",$shList);

     
        $this->assign("page", $show);

        $this->display();
	}
	
	public function GetStatus($opstatus){
		
		if($opstatus==0)
			return "未审核";
		if($opstatus==1)
			return "未通过";
		if($opstatus==2)
			return "已通过";
	}

  
  
  
	
    public function shenjidel()
    {

        $this->LoginTrue();

        $id = $_GET["uid"];

        $log = M("usersjinfo")->where("id={$id}")->delete();

        $this->success("删除成功", U("orderlist"));
    }
	
    public function tousudel()
    {

        $this->LoginTrue();

        $id = $_GET["uid"];

        $log = M("tousuinfo")->where("id={$id}")->delete();

        $this->success("删除成功", U("tslists"));
    }


    public function shengjishenhe()
    {

        $this->LoginTrue();
        //echo $_GET["uid"];

        $id = $_GET["uid"];

		
		
		$shList = M("usersjinfo")->where("id='$id' and (status1=0 or status2=0) ")->order("id desc")->find();
		if(!$shList){
			$this->error("已经审核过");
		}
		$op = 2;
		M("usersjinfo")->startTrans();
		$save = array(
			"status1" => 2,
			"status2" => 2,
			"opuser" => "System",
			"shtime1" => time(),
			"shtime2" => time()
		);
		if(M("usersjinfo")->where("id=$id")->save($save)){
			if($op==2){
				M("users")->where("id=$shList[user_id]")->save(array("standardlevel"=>$shList['targetlevel']));
				
				$msgtext = "通过：【创客联盟】您的审核已通过，恭喜您成功升级为".$shList['targetlevel']."级会员。";
				$this->SendMsg($shList['loginname'],$msgtext);
			}
			
			M("usersjinfo")->commit();
			$this->success("操作成功",U("orderlist"));
			exit;
		}
		else{
			$this->error("操作失败",U("orderlist"));
		}
        //var_dump($userInfo);
    }

    
        /**
     *  订单列表pp
     **/
    public function order_list()
    {
        if ($_GET['id'] && !$_POST['update_order']) {
            $order = M('order_info')->where("id='{$_GET[id]}'")->find();
            $order_status = $order['order_status'] . $order['shipping_status'] . $order['pay_status'];
            $this->assign('order_status_num', $order_status);
            switch ($order_status) {
                case 102:
                    $this->assign('order_status', '已付款,待发货');
                    break;
                case 521:
                    $this->assign('order_status', '已付款,已发货,待收货');
                    break;
                case 522:
                    $this->assign('order_status', '已付款,已发货,已收货');
                    break;
            }
            $this->assign('order', $order);
            $this->display('order_handle');
            die;
        } elseif ($_POST['update_order'] == 'update_order') {
            if (!$_POST['kd_name'] || !$_POST['kd_order']) {
                $this->success('没有发货信息,暂不能收货');
                die;
            }
            //更新快递信息
            $data = array(
                'order_status' => 5,
                'shipping_status' => 2,
                'pay_status' => 2,
                'confirm_time' => time(),
            );
            if (M('order_info')->where("id='$_POST[order_id]'")->save($data)) {
                $this->success('确认收货成功', U('User/order_list'));
            } else {
                $this->success('操作失败,请联系管理员');
            }
            die;
        } else {
            //获取订购的订单
            $order_list = M('order_info')->where("loginname='$_SESSION[nvip_nvip_member_User]'")->select();
            foreach ($order_list as &$v) {
                $order_status = $v['order_status'] . $v['shipping_status'] . $v['pay_status'];
                switch ($order_status) {
                    case 102:
                        $v['order_status_pp'] = '已付款,待发货';
                        break;
                    case 521:
                        $v['order_status_pp'] = '已付款,已发货,待收货';
                        break;
                    case 522:
                        $v['order_status_pp'] = '已付款,已发货,已收货';
                        break;
                }
            }
            $this->assign('order_list', $order_list);
            $this->display();
        }


    }

}